package hr.functional.teststeps;

import cucumber.annotation.Before;
import cucumber.annotation.en.Given;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.util.LinkedList;
import java.util.List;

import static hr.functional.teststeps.SeleniumSteps.Employee;

public class JdbcSteps {

    public ApplicationContext context;
    public JdbcTemplate jdbcTemplate;

    @Before
    public void prepare_context() {
        context = new ClassPathXmlApplicationContext("acceptance-test-context.xml");
        jdbcTemplate = new JdbcTemplate((DataSource) context.getBean("dataSource"));
    }

    @Given("^employees in database$")
    public void employees_in_database(List<Employee> employees) {
        jdbcTemplate.update("delete from Employee");
        int index = 1;
        List<String> sqlStatements = new LinkedList<String>();
        for (Employee employee : employees) {
            sqlStatements.add(buildSql(index++, employee));
        }
        jdbcTemplate.batchUpdate(sqlStatements.toArray(new String[sqlStatements.size()]));
    }

    @Given("^empty database$")
    public void empty_database() {
        jdbcTemplate.update("delete from Employee");
    }

    private String buildSql(int index, Employee employee) {
        return String.format("insert into EMPLOYEE (id, firstName, lastName, jobTitle) values (%1$d, '%2$s', '%3$s', '%4$s')",
                index, employee.firstName, employee.lastName, employee.jobTitle);
    }

}